package com.veer.shop.config;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.veer.shop.annotation.CurrentUser;
import com.veer.shop.utils.RedisUtil;
import com.veer.shop.pojo.CurrentUserInfo;
/**
 * 后台当前用户信息参数注解
 * 
 * @author WangBin
 * 2020年12月4日-下午4:57:03
 */
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ObjectMapper jackJsonMapper;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(CurrentUser.class);
    }

    /**
     * 获取当前用户信息
     */
    @Override
    public CurrentUserInfo resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                    NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    	HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
    	String token = request.getHeader(Constants.HTTP_HEADER_AUTHORIZATION).replace("Bearer ", "");
        CurrentUserInfo currentUserInfo = new CurrentUserInfo();
        if(StringUtils.isEmpty(token))return currentUserInfo;
        String userJsonStr = redisUtil.get(token);
        if(StringUtils.isEmpty(userJsonStr))return currentUserInfo;
        currentUserInfo = jackJsonMapper.readValue(userJsonStr, CurrentUserInfo.class);
        return currentUserInfo;
    }

}